﻿//using AlStudy.文心一言;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Ollama;
using RestSharp;
using System.Text;

namespace AlStudy
{
    internal class Program
    {
        private static readonly HttpClient client = new HttpClient();

        static async Task Main(string[] args)
        {
            try
            {
                #region     文心一言的调用
                ///*定义输入字符串为"C# 调用文心一言api"\
                //调用文心一言API的异步方法并等待返回结果，结果存储在response变量中\*/

                ///**/
                //string input = "C# 调用文心一言api";
                //string response = await WenxinYiyanApi.CallWenxinYiyanApiAsync(input);


                ///**/


                //Console.WriteLine("API Response: ");
                //Console.WriteLine(response);


                #endregion

                string modelName = "qwen2:7b";
                using var ollama = new OllamaApiClient(baseUri: new Uri("http://127.0.0.1:11434/api"));

                Console.WriteLine("开始对话！！！");
                string userInput = "";
                do
                {
                    Console.WriteLine("User:");
                    userInput = Console.ReadLine()!;
                    var enumerable = ollama.Completions.GenerateCompletionAsync(modelName, userInput);
                    Console.WriteLine("Agent:");
                    await foreach (var response in enumerable)
                    {
                        Console.Write($"{response.Response}");
                    }
                    Console.WriteLine();

                } while (!string.Equals(userInput, "exit", StringComparison.OrdinalIgnoreCase));
                Console.WriteLine("对话结束！！！");





            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        // 定义响应模型（根据你的API响应结构来定义）
        public class YourResponseModel
        {
            // 例如：
            public string GeneratedText { get; set; }
            // 其他可能的响应属性...
        }

        //const string API_KEY = "Ko6v8Ee1smrkct6t1eQEkCow";
        //const string SECRET_KEY = "ZsQzz6COT4TiE0ToYWD3vxJxaomE4xHI";
        //static void Main(string[] args)
        //{
        //    var token = GetAccessToken();
        //    //文心一言会根据前面的问答回复信息
        //    List<ChatVO> messages = new List<ChatVO>();
        //    //用户问1
        //    messages.Add(new ChatVO { role = "user", content = "父亲的英文是什么？" });
        //    //温馨一言答1
        //    messages.Add(new ChatVO { role = "assistant", content = "父亲是father" });
        //    //用户问2
        //    messages.Add(new ChatVO { role = "user", content = "那母亲呢？" });
        //    var chatMsg = GetChat(token, "13900000011", messages);
        //    Console.WriteLine(chatMsg);
        //    Console.ReadLine();
        //}
        //static string GetChat(string accessToken, string userId, List<ChatVO> messages)
        //{
        //    WxyyChatReq wxyyChatReq = new WxyyChatReq
        //    {
        //        user_id = userId,
        //        messages = messages,
        //        temperature = 0.95,
        //        top_p = 0.8,
        //        penalty_score = 1,
        //        disable_search = false,
        //        enable_citation = false,
        //        stream = false
        //    };
        //    var url = $"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token={accessToken}";
        //    var client = new RestSharp.RestClient(url);
        //    //client.Timeout = -1;
        //    var request = new RestSharp.RestRequest(RestSharp.Method.Post.ToString());
        //    request.AddHeader("Content-Type", "application/json");
        //    var body = JsonConvert.SerializeObject(wxyyChatReq);
        //    request.AddParameter("application/json", body, ParameterType.RequestBody);
        //    var response = client.Execute(request);
        //    return response.Content;
        //}
        ///**
        //* 使用 AK，SK 生成鉴权签名（Access Token）
        //* @return 鉴权签名信息（Access Token）
        //*/
        //static string GetAccessToken()
        //{
        //    var url = "https://aip.baidubce.com/oauth/2.0/token";
        //    var client = new RestClient(url);
        //    //client.Timeout = -1;
        //    var request = new RestRequest(Method.Post.ToString());
        //    request.AddParameter("grant_type", "client_credentials");
        //    request.AddParameter("client_id", API_KEY);
        //    request.AddParameter("client_secret", SECRET_KEY);
        //    var response = client.Execute(request);
        //    Console.WriteLine(response.Content);
        //    var result = JsonConvert.DeserializeObject<dynamic>(response.Content);
        //    return result.access_token.ToString();
        //}
    }

    public class WxyyChatReq
    {
        public string user_id { get; set; }
        public double temperature { get; set; }
        public double top_p { get; set; }
        public double penalty_score { get; set; }
        public bool disable_search { get; set; }
        public bool enable_citation { get; set; }

        //是否流式处理
        public bool stream { get; set; }

        //最大输出token数（token:字数一般为1:2）
        //public int max_output_tokens { get; set; }  

        public List<ChatVO> messages { get; set; }
    }
    public class ChatVO
    {
        public string role { get; set; }
        public string content { get; set; }
    }

}
